package com.wdh.kjs.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.http.response.NotifyDownload;
import com.wdh.kjs.model.JsonModel;
import com.wdh.kjs.util.ToastUtils;

/**
 * Created by feifei on 2016/4/27.
 */
public class MoreActivity extends BaseTopActivity implements View.OnClickListener {
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 17;
    private LinearLayout linearLayout;
    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private LinearLayout linearLayout3;
    private LinearLayout linearLayout4;
    private LinearLayout linearLayout5;
    private LinearLayout moreactivity_linear6;
    private LinearLayout linearLayoutnews;
    private LinearLayout moreactivity_pingtaidongtai;
    private Intent intent;
    private SharedPreferences sharedPreferences;
    private String loginToken;
    private String version;
    private String nowversion;
    private PackageInfo packInfo;
    private JsonModel jsonModel;
    private SharedPreferences preferences;
    private SharedPreferences[]  preferencesversion;
    private TextView tv_nowversion;
    private SharedPreferences.Editor editor;
    private String url;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.moreactivity);
        sharedPreferences = getSharedPreferences("logininfo", MODE_PRIVATE);
        loginToken = sharedPreferences.getString("loginToken", "");

        final SharedPreferences[] preferencesversion = {getSharedPreferences("Version", MODE_PRIVATE)};
        nowversion = preferencesversion[0].getString("version", "1.0");

//        preferencesversion[0]= getSharedPreferences("Version", MODE_PRIVATE);
//        nowversion = preferencesversion[0].getString("version", "1.0");
        initview();
        tv_nowversion.setText(nowversion);
        if (loginToken.equals("")){
            linearLayout.setVisibility(View.GONE);
        }else{
            linearLayout.setVisibility(View.VISIBLE);}
        initwidge();
    }
    private void initwidge() {
        linearLayout.setOnClickListener(this);
        linearLayout1.setOnClickListener(this);
        linearLayout2.setOnClickListener(this);
        linearLayout3.setOnClickListener(this);
        linearLayout4.setOnClickListener(this);
        linearLayout5.setOnClickListener(this);
        moreactivity_linear6.setOnClickListener(this);
        linearLayoutnews.setOnClickListener(this);
        moreactivity_pingtaidongtai.setOnClickListener(this);
    }

    private void initview() {
        initTopBar("更多");
        tv_nowversion = (TextView) findViewById(R.id.tv_nowversion);
        moreactivity_pingtaidongtai = (LinearLayout) findViewById(R.id.moreactivity_pingtaidongtai);
        linearLayout = (LinearLayout) findViewById(R.id.moreactivity_linear);
        linearLayout1 = (LinearLayout) findViewById(R.id.moreactivity_linear1);
        linearLayout2 = (LinearLayout) findViewById(R.id.moreactivity_linear2);
        linearLayout3 = (LinearLayout) findViewById(R.id.moreactivity_linear3);
        linearLayout4 = (LinearLayout) findViewById(R.id.moreactivity_linear4);
        linearLayout5 = (LinearLayout) findViewById(R.id.moreactivity_linear5);
        moreactivity_linear6 = (LinearLayout) findViewById(R.id.moreactivity_linear6);
        linearLayoutnews = (LinearLayout) findViewById(R.id.moreactivity_newsLinear);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.moreactivity_linear6:


                final SharedPreferences[] preferences = {getSharedPreferences("Version", MODE_PRIVATE)};
                version = preferences[0].getString("version", "");
                PackageManager manager = this.getPackageManager();
                PackageInfo info = null;
                try {
                    info = manager.getPackageInfo(this.getPackageName(), 0);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                final String version = info.versionName;

                new HttpUtils().send(HttpRequest.HttpMethod.POST, Httpurl.URL_UPDATE, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Gson gson = new Gson();

                         jsonModel = gson.fromJson(responseInfo.result, JsonModel.class);
                        if (jsonModel.isSuccess()) {
                            url = Httpurl.HOST + jsonModel.getAndroidVersionInfo().getAndroidUrl();


                            String versionCode = getVersionCode(); // 当前本地版本
                            String currentCode = jsonModel.getAndroidVersionInfo().getAndroidVersionNum(); // 服务器发布版本
                            if (Double.parseDouble(versionCode) >= Double.parseDouble(currentCode)) {
                                Toast.makeText(MoreActivity.this,
                                        "当前版本为" + versionCode + "，已是最新!", Toast.LENGTH_SHORT)
                                        .show();
                            } else {
                                new AlertDialog.Builder(
                                        MoreActivity.this)
                                        .setTitle("新版本")
                                        .setMessage(
                                                "当前最新版本为"
                                                        + jsonModel.getAndroidVersionInfo().getAndroidVersionNum()
                                                        + "\n更新内容包括:" + jsonModel.getAndroidVersionInfo().getAndroidVersionInfo() + "\n建议更新")
                                        .setPositiveButton("确定",
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(
                                                            DialogInterface dialog,
                                                            int which) {
                                                        if (ContextCompat.checkSelfPermission(MoreActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                                                != PackageManager.PERMISSION_GRANTED) {
                                                            //申请WRITE_EXTERNAL_STORAGE权限
                                                            ActivityCompat.requestPermissions(MoreActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
                                                        }

                                                            NotifyDownload down = new NotifyDownload(
                                                                    MoreActivity.this);
                                                            down.startDownload(
                                                                    MoreActivity.this,
                                                                    url);
                                                        }
                                                })
                                        .setNegativeButton("取消", null)
                                        .create().show();
                            }
                            preferences[0] = getSharedPreferences("Version", Context.MODE_PRIVATE);
                            editor = preferences[0].edit();

                            editor.putString("version", jsonModel.getAndroidVersionInfo().getAndroidVersionNum());

                            editor.commit();
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {


                            ToastUtils.showShort(MoreActivity.this, "网络异常!");

                    }
                });


                break;
            case R.id.moreactivity_pingtaidongtai:
                intent = new Intent(MoreActivity.this, DongtaiActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear:
                intent = new Intent(MoreActivity.this, NoticeActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear1:
                intent = new Intent(MoreActivity.this, HelpCenterActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear2:
                intent = new Intent(MoreActivity.this, PlatformIntroActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear3:
                intent = new Intent(MoreActivity.this, ConnectUsActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear4:
                intent = new Intent(MoreActivity.this, MessagePushActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_linear5:
                intent = new Intent(MoreActivity.this, FeedBackActivity.class);
                startActivity(intent);
                break;
            case R.id.moreactivity_newsLinear: {
                intent = new Intent(MoreActivity.this, NewsActivity.class);
                startActivity(intent);
                break;
            }
            default: {
                break;
            }
        }
    }
    /*
           * 获取当前程序的版本号
           */
    private String getVersionCode() {
        // 获取packagemanager的实例
        PackageManager packageManager = MoreActivity.this
                .getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息

        try {
            packInfo = packageManager.getPackageInfo(
                    MoreActivity.this.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return packInfo.versionName;

    }

    /*
     * 获取当前程序的版本名
     */
    private String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = MoreActivity.this
                .getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo;
        try {
            packInfo = packageManager.getPackageInfo(
                    MoreActivity.this.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode,grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else {
                // Permission Denied
            }
        }
    }
}
